import subprocess
import platform
import json


class ProcessInfo:
    """进程信息获取器"""

    @classmethod
    def get_process_info(cls, port: int) -> str:
        """获取进程信息"""
        try:
            if platform.system() == "Windows":
                return cls._get_windows_process_details(port)
            else:
                return cls._get_unix_process_details(port)
        except Exception:
            return "无法获取进程信息"

    @classmethod
    def _get_windows_process_details(cls, port: int) -> str:
        """获取Windows进程详细信息"""
        try:
            # 使用netstat获取PID
            netstat_cmd = f"netstat -ano | findstr :{port}"
            result = subprocess.run(
                netstat_cmd,
                shell=True,
                capture_output=True,
                text=True,
                encoding="utf-8",
                errors="ignore",
            )

            if result.returncode == 0 and result.stdout.strip():
                lines = result.stdout.strip().split("\n")
                for line in lines:
                    if f":{port}" in line and "LISTENING" in line:
                        parts = line.split()
                        if len(parts) >= 5:
                            pid = parts[-1]

                            # 使用PowerShell获取详细进程信息
                            ps_cmd = f'powershell "Get-Process -Id {pid} | Select-Object Name, Path, CommandLine | ConvertTo-Json"'
                            ps_result = subprocess.run(
                                ps_cmd,
                                shell=True,
                                capture_output=True,
                                text=True,
                                encoding="utf-8",
                                errors="ignore",
                            )

                            if ps_result.returncode == 0:
                                try:
                                    process_data = json.loads(ps_result.stdout)
                                    name = process_data.get("Name", "Unknown")
                                    path = process_data.get("Path", "Unknown")
                                    return f"{name} | PID: {pid} | {path}"
                                except:
                                    pass

                            # 备用方法：使用tasklist
                            tasklist_cmd = f'tasklist /FI "PID eq {pid}" /FO CSV'
                            tasklist_result = subprocess.run(
                                tasklist_cmd,
                                shell=True,
                                capture_output=True,
                                text=True,
                                encoding="utf-8",
                                errors="ignore",
                            )

                            if tasklist_result.returncode == 0:
                                lines = tasklist_result.stdout.strip().split("\n")
                                if len(lines) >= 2:
                                    data = lines[1].replace('"', "").split(",")
                                    if len(data) >= 2:
                                        return f"{data[0]} | PID: {pid}"

                            return f"PID: {pid}"

            return "无法获取进程信息"

        except Exception:
            return "无法获取进程信息"

    @classmethod
    def _get_unix_process_details(cls, port: int) -> str:
        """获取Unix/Linux进程详细信息"""
        try:
            # 使用lsof获取进程信息
            lsof_cmd = f"lsof -i :{port}"
            result = subprocess.run(
                lsof_cmd,
                shell=True,
                capture_output=True,
                text=True,
                encoding="utf-8",
                errors="ignore",
            )

            if result.returncode == 0 and result.stdout.strip():
                lines = result.stdout.strip().split("\n")
                if len(lines) >= 2:
                    parts = lines[1].split()
                    if len(parts) >= 2:
                        process_name = parts[0]
                        pid = parts[1]

                        # 尝试获取进程路径
                        try:
                            path_cmd = f"readlink -f /proc/{pid}/exe"
                            path_result = subprocess.run(
                                path_cmd,
                                shell=True,
                                capture_output=True,
                                text=True,
                                encoding="utf-8",
                                errors="ignore",
                            )

                            if path_result.returncode == 0:
                                path = path_result.stdout.strip()
                                return f"{process_name} | PID: {pid} | {path}"
                        except:
                            pass

                        return f"{process_name} | PID: {pid}"

            return "无法获取进程信息"

        except Exception:
            return "无法获取进程信息"
